package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.shopCarMapper;
import com.sky.result.Result;
import com.sky.service.impl.shopCarServiceable;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@RequestMapping("/user/shoppingCart")
@RestController
@Slf4j
@Api(tags = "购物车接口")
public class shopCarController {
    @Autowired
    private shopCarServiceable shopCarServiceable;
    @Autowired
    private shopCarMapper shopCarMapper;

    @PostMapping("/add")
    @ApiOperation(value = "添加购物车")
    public Result addShopCar(@RequestBody ShoppingCartDTO shoppingCartDTO) {
        shopCarServiceable.addService(shoppingCartDTO);
        return Result.success();
    }

    @GetMapping("/list")
    @ApiOperation(value = "查看购物车")
    public Result listShopCar() {
        List<ShoppingCart> page = shopCarMapper.page(BaseContext.getCurrentId());
        log.info(page.toString());
        return Result.success(page);
    }

    @ApiOperation(value = "删除一个")
    @PostMapping("/sub")
    public Result deleteShopCar(@RequestBody ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart shoppingCart=new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        shoppingCart.setUserId(BaseContext.getCurrentId());
        ShoppingCart i = shopCarMapper.select(shoppingCart);
        Integer number = i.getNumber();
        if(number>1){
            //BigDecimal price = i.getAmount().divide(BigDecimal.valueOf(i.getNumber()));
            //价格和数量变化
            i.setNumber(i.getNumber() - 1);
            i.setCreateTime(LocalDateTime.now());
            //i.setAmount(price.multiply(BigDecimal.valueOf(i.getNumber())));
            shopCarMapper.updateShop(i);
        }else{
            shopCarMapper.deleteOne(shoppingCartDTO, BaseContext.getCurrentId());
        }


        return Result.success();
    }
    @ApiOperation(value = "删除所有")
    @DeleteMapping("/clean")
    public Result deleteAll(){
        shopCarMapper.deleteOne(new ShoppingCartDTO(), BaseContext.getCurrentId());
        return Result.success();
    }
}
